﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VAdvantage.Logging;
using VAdvantage.Grids;
using VAdvantage.Model;
using System.Windows.Data;
using VAdvantage.DataBase;
using System.Windows.Controls;
using System.Windows;

namespace VAdvantage.Controls
{
    public class VImage : CButton, IControl,IEditingControl
    {

        #region Declaration

        /** WindowNo                */
        private int _windowNo;
        /** The Image Model         */
        private MImage _mImage = null;
        /** Mandatory flag          */
        private bool _mandatory = false;
        /** Column Name             */
        private String _columnName = "AD_Image_ID";
        /**	Logger			*/
        private static VLogger log = VLogger.GetVLogger(typeof(VImage).FullName);

        private bool _readOnly;

        /** Grid Field				*/
        private GridField _field = null;

        private Binding binding;

        private Image img = new Image();


        #endregion

        public static readonly DependencyProperty ValueChangedProperty =
      DependencyProperty.Register("Value", typeof(object), typeof(VAdvantage.Controls.VImage), new PropertyMetadata((o, e) =>
      {
          ((VImage)o).SetValue((Object)e.NewValue);

      }));


        public Object Value
        {
            get
            {
                return ((Object)GetValue(VImage.ValueChangedProperty));
            }
            set
            {
                SetValue(VImage.ValueChangedProperty, value);
            }
        }

        /// <summary>
        /// default constructor
        /// </summary>
        /// <summary>
        /// Image Editor
        /// </summary>
        /// <param name="columnName">olumn name</param>
        /// <param name="WindowNo">windowNo window no</param>
        public VImage(String columnName, int windowNo)
        {
            //super("-");
            _columnName = columnName;
            _windowNo = windowNo;
            //super.addActionListener(this);

            if (!GlobalVariable.IsVisualEditor)
            {
                this.Click += new System.Windows.RoutedEventHandler(VImage_Click);
            }
        }

        public VImage()
        {

        }

        void VImage_Click(object sender, EventArgs e)
        {
            Dialogs.VImageDialog vid = new Dialogs.VImageDialog(_mImage);
            vid.Closed += (s, eh) =>
                {
                    if (vid.DialogResult != null && (bool)vid.DialogResult)
                    {
                        int AD_Image_ID = vid.GetAD_Image_ID();
                        int? newValue = null;
                        if (AD_Image_ID != 0)
                            newValue = AD_Image_ID;
                        //
                        _mImage = null;	//	force reload

                        if (EditingControlDataGridView != null)
                        {
                            SetValueInDataGridColumn(newValue);
                            EditingControlDataGridView.RaiseCellValueChanged(this);
                            _field.SetValue(newValue);
                            ((DataUtil.DataObject)EditingControlDataGridView.SelectedItem).SetFieldValue(_columnName.ToUpper(), newValue);
                        }
                        else
                        {

                            SetValue(newValue);	//	set explicitly
                            if (VetoableChangeListener != null)
                            {
                                VetoableChangeListener(this, EventArgs.Empty);
                            }
                        }
                    }
                };
        }

        #region "IControl"

        public event EventHandler VetoableChangeListener;

        public int GetDisplayType()
        {
            return Classes.DisplayType.Image;
        }

        public void SetDisplayType(int displayType)
        {
            //throw new NotImplementedException();
        }

        public bool GetIsReadonly()
        {
            return !this.IsEnabled;
        }

        public void SetReadOnly(bool readOnly)
        {
            this.IsEnabled = !readOnly;
        }

        public GridField GetField()
        {
            return _field;
        }

        public void SetField(GridField mField)
        {
            if (mField != null)
                _windowNo = mField.GetWindowNo();
            _field = mField;
        }

        public string GetName()
        {
            return this._columnName;
        }

        public void SetName(string name)
        {
            this._columnName = name;
        }

        public string GetText()
        {
            if (_mImage == null || _mImage.Get_ID() == 0)
                return "";
            return _mImage.GetName();
        }

        public object GetValue()
        {
            if (currentValue == 0)
                return null;
            return currentValue;
        }

        private int currentValue = 0;
        public void SetValue(object value)
        {
            log.Fine("=" + value);
            int newValue = 0;
            if (value is int)
                newValue = (int)value;
            else
            {
                try
                {
                    newValue = int.Parse(value.ToString());
                }
                catch
                {

                }
            }
            if (newValue == 0)
            {
                _mImage = null;
                this.Content = "-";
                img.Source = null;
                currentValue = 0;
                //this.Image = null;
                //super.setToolTipText(null);
                return;
            }
            //  Get/Create Image
            if (_mImage == null || newValue != currentValue)
            {
                this.Content = img;
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                    {
                        _mImage = MImage.Get(Utility.Envs.GetCtx(), newValue);
                        Dispatcher.BeginInvoke(() => img.Source = _mImage.GetImage()
                        );
                    });
            }
            currentValue = newValue;
            if(_mImage!=null)
            log.Fine(_mImage.ToString());
            //this.Text = "";
            //super.setText(null);
            
            //super.setToolTipText(m_mImage.getName());
            //invalidate();
        }

        public bool GetIsMandatory()
        {
            return _mandatory;
        }

        public void SetIsMandatory(bool value)
        {
            _mandatory = value;
        }

        public void SetBackGround(bool value)
        {
            //throw new NotImplementedException();
        }

        public string GetSelectedText()
        {
            return "";// throw new NotImplementedException();
        }

        public bool IsDisabled()
        {
            return !this.IsEnabled;
        }

        public void SetDisabled(bool disabled)
        {
            this.IsEnabled = !disabled;
        }

        public int GetTabIndex()
        {
            return this.TabIndex;
        }

        public void SetTabindex(int tabindex)
        {
            this.TabIndex = tabindex;
        }

        public bool Multiline
        {
            get
            {
                return false;
            }
            set
            {
                //throw new NotImplementedException();
            }
        }

        public bool Visible
        {
            get
            {
                return Visibility == System.Windows.Visibility.Visible;
            }
            set
            {
                this.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            }
        }

        public bool Focused
        {
            get { return true; }
        }

        public string BindValue
        {
            set {

                binding = new Binding(value);
                binding.Mode = BindingMode.OneWay;
                this.SetBinding(VImage.ValueChangedProperty, binding);
            }
        }

        public void Dispose()
        {
            img = null;
            binding = null;

        }
        #endregion

        public VDataGrid EditingControlDataGridView
        {
            get;
            set;

        }

        public void SetValueInDataGridColumn(object value)
        {
            SetValue(value);
        }
    }
}
